<template>
  <div class="upload-page">
    <!-- 用户配额信息 -->
    <div class="quota-info" v-if="userStore.user">
      <div class="quota-card">
        <div class="quota-text">
          <span class="quota-label">今日剩余次数</span>
          <span class="quota-count">{{ userStore.remainingQuota }}</span>
        </div>
        <div class="quota-progress">
          <van-progress 
            :percentage="(userStore.user.used_quota / userStore.user.daily_quota) * 100"
            color="#6366f1"
            track-color="#f0f0f0"
          />
        </div>
      </div>
    </div>

    <!-- 上传区域 -->
    <div class="upload-section">
      <h2 class="section-title">上传猫咪照片</h2>
      <p class="section-desc">选择一张清晰的猫咪照片，AI将为它打造专属风格</p>
      
      <van-uploader
        v-model="fileList"
        :after-read="afterRead"
        :before-delete="beforeDelete"
        :max-count="1"
        :max-size="10 * 1024 * 1024"
        upload-text="点击上传"
        @oversize="onOversize"
        class="custom-uploader"
      >
        <template v-if="!uploadedImage">
          <div class="upload-placeholder">
            <van-icon name="photograph" class="upload-icon" />
            <p class="upload-text">点击上传猫咪照片</p>
            <p class="upload-tips">支持 JPG、PNG 格式，最大 10MB</p>
          </div>
        </template>
      </van-uploader>
      
      <!-- 上传成功后显示 -->
      <div v-if="uploadedImage" class="upload-success">
        <div class="uploaded-image">
          <img :src="uploadedImage.url" alt="上传的图片" />
          <van-button 
            icon="cross" 
            type="danger" 
            size="small" 
            round 
            @click="removeImage"
            class="remove-btn"
          />
        </div>
        <p class="upload-success-text">照片上传成功！请选择风格</p>
      </div>
    </div>

    <!-- 风格选择 -->
    <div class="style-section" v-if="uploadedImage">
      <div class="section-header">
        <h2 class="section-title">选择生成风格</h2>
        <van-button 
          type="primary" 
          size="small" 
          @click="showAllStyles"
          class="more-btn"
        >
          查看全部
        </van-button>
      </div>
      
      <!-- 分类筛选 -->
      <div class="category-tabs" v-if="categories.length > 0">
        <van-tabs v-model:active="activeCategory" @click-tab="onCategoryChange">
          <van-tab name="" title="全部"></van-tab>
          <van-tab 
            v-for="category in categories" 
            :key="category.key"
            :name="category.key" 
            :title="category.name"
          ></van-tab>
        </van-tabs>
      </div>
      
      <!-- 风格网格 -->
      <div class="styles-grid" v-if="filteredStyles.length > 0">
        <div 
          v-for="style in filteredStyles" 
          :key="style.id"
          class="style-item"
          :class="{ active: selectedStyle?.id === style.id }"
          @click="selectStyle(style)"
        >
          <div class="style-image">
            <img 
              :src="style.thumbnail_url || style.preview_image_url || '/placeholder.jpg'" 
              :alt="style.name"
            />
            <div class="style-premium" v-if="style.is_premium">
              <van-icon name="diamond" />
            </div>
          </div>
          <p class="style-name">{{ style.name }}</p>
        </div>
      </div>
      
      <van-loading v-else class="loading-center" />
    </div>

    <!-- 自定义提示词 -->
    <div class="prompt-section" v-if="selectedStyle">
      <h3 class="prompt-title">自定义描述（可选）</h3>
      <van-field
        v-model="customPrompt"
        type="textarea"
        placeholder="添加更多细节描述，如：戴着蝴蝶结、背景是花园等"
        rows="3"
        maxlength="200"
        show-word-limit
        class="prompt-input"
      />
    </div>

    <!-- 生成按钮 -->
    <div class="generate-section" v-if="uploadedImage && selectedStyle">
      <van-button 
        type="primary" 
        size="large" 
        block 
        round 
        :loading="generating"
        :disabled="!userStore.canGenerate"
        @click="generateImage"
        class="generate-btn"
      >
        <template v-if="generating">生成中...</template>
        <template v-else-if="!userStore.canGenerate">今日次数已用完</template>
        <template v-else>开始生成 ({{ userStore.remainingQuota }}次剩余)</template>
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useImageStore } from '../stores/image'
import { useUserStore } from '../stores/user'
import { uploadImageApi } from '../api/image'
import type { StyleTemplate, UploaderFileListItem } from '../types'
import { Toast, Dialog } from 'vant'

const router = useRouter()
const imageStore = useImageStore()
const userStore = useUserStore()

const fileList = ref([])
const uploadedImage = ref(imageStore.uploadedImage)
const selectedStyle = ref(imageStore.selectedStyle)
const customPrompt = ref('')
const generating = ref(false)
const activeCategory = ref('')
const categories = ref([])

// 计算属性
const filteredStyles = computed(() => {
  if (!activeCategory.value) {
    return imageStore.styleTemplates.slice(0, 6) // 显示前6个
  }
  return imageStore.styleTemplates.filter(style => 
    style.category === activeCategory.value
  ).slice(0, 6)
})

// 文件上传后处理
const afterRead = async (file: UploaderFileListItem) => {
  if (!file.file) return
  
  try {
    Toast.loading('上传中...')
    
    const result = await uploadImageApi(file.file)
    
    Toast.clear()
    
    if (result.success) {
      uploadedImage.value = {
        url: result.data.file_url,
        filename: result.data.filename
      }
      imageStore.setUploadedImage(uploadedImage.value)
      Toast.success('上传成功')
    }
  } catch (error: any) {
    Toast.clear()
    Toast.fail(error.message || '上传失败')
    fileList.value = []
  }
}

// 删除图片前确认
const beforeDelete = () => {
  return Dialog.confirm({
    title: '确认删除',
    message: '删除后需要重新上传，确定删除吗？'
  })
}

// 移除图片
const removeImage = () => {
  uploadedImage.value = null
  selectedStyle.value = null
  fileList.value = []
  imageStore.setUploadedImage(null)
  imageStore.setSelectedStyle(null)
}

// 文件大小超限
const onOversize = () => {
  Toast.fail('文件大小不能超过 10MB')
}

// 选择风格
const selectStyle = (style: StyleTemplate) => {
  selectedStyle.value = style
  imageStore.setSelectedStyle(style)
}

// 查看所有风格
const showAllStyles = () => {
  router.push('/style')
}

// 分类切换
const onCategoryChange = async (name: string) => {
  activeCategory.value = name
  await loadStyles(name)
}

// 生成图片
const generateImage = async () => {
  if (!uploadedImage.value || !selectedStyle.value) {
    Toast.fail('请先上传图片并选择风格')
    return
  }

  if (!userStore.canGenerate) {
    Toast.fail('今日生成次数已用完')
    return
  }

  generating.value = true

  try {
    const result = await imageStore.generateImage({
      original_image_url: uploadedImage.value.url,
      style_template_id: selectedStyle.value.id,
      custom_prompt: customPrompt.value.trim()
    })

    if (result.success) {
      router.push(`/generate?taskId=${result.taskId}`)
    } else {
      Toast.fail(result.error || '生成失败')
    }
  } catch (error: any) {
    Toast.fail(error.message || '生成失败')
  } finally {
    generating.value = false
  }
}

// 加载风格模板
const loadStyles = async (category?: string) => {
  const result = await imageStore.loadStyleTemplates(category)
  if (!result.success) {
    Toast.fail(result.error || '加载风格失败')
  }
}

// 加载分类
const loadCategories = async () => {
  const result = await imageStore.loadCategories()
  if (result.success) {
    categories.value = imageStore.categories
  }
}

onMounted(() => {
  loadStyles()
  loadCategories()
})
</script>

<style scoped>
.upload-page {
  padding: 20px;
  min-height: 100vh;
  background: #f7f8fa;
}

.quota-info {
  margin-bottom: 20px;
}

.quota-card {
  background: white;
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.quota-text {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.quota-label {
  font-size: 14px;
  color: #666;
}

.quota-count {
  font-size: 18px;
  font-weight: bold;
  color: #6366f1;
}

.upload-section {
  background: white;
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.section-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 20px;
}

.custom-uploader {
  margin-bottom: 20px;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 20px;
  border: 2px dashed #ddd;
  border-radius: 12px;
  background: #fafafa;
}

.upload-icon {
  font-size: 48px;
  color: #ccc;
  margin-bottom: 16px;
}

.upload-text {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
}

.upload-tips {
  font-size: 12px;
  color: #999;
}

.upload-success {
  text-align: center;
}

.uploaded-image {
  position: relative;
  display: inline-block;
  margin-bottom: 16px;
}

.uploaded-image img {
  width: 200px;
  height: 200px;
  object-fit: cover;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.remove-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 24px;
  height: 24px;
  min-width: 24px;
}

.upload-success-text {
  font-size: 14px;
  color: #52c41a;
  font-weight: bold;
}

.style-section {
  background: white;
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.more-btn {
  font-size: 12px;
}

.category-tabs {
  margin-bottom: 20px;
}

.styles-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
}

.style-item {
  text-align: center;
  cursor: pointer;
  transition: transform 0.2s;
}

.style-item.active .style-image {
  border-color: #6366f1;
  box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2);
}

.style-item:active {
  transform: scale(0.95);
}

.style-image {
  position: relative;
  width: 100%;
  height: 80px;
  border: 2px solid transparent;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 8px;
}

.style-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.style-premium {
  position: absolute;
  top: 4px;
  right: 4px;
  background: linear-gradient(45deg, #ffd700, #ffed4a);
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.style-premium .van-icon {
  font-size: 12px;
  color: #fff;
}

.style-name {
  font-size: 12px;
  color: #333;
  font-weight: 500;
}

.prompt-section {
  background: white;
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.prompt-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
}

.generate-section {
  position: sticky;
  bottom: 0;
  background: white;
  padding: 16px 20px;
  border-top: 1px solid #eee;
}

.generate-btn {
  background: linear-gradient(45deg, #6366f1, #8b5cf6);
  border: none;
  font-weight: bold;
}

.loading-center {
  display: flex;
  justify-content: center;
  padding: 40px;
}
</style>